package com.example.persion.Shiro;

import cn.hutool.core.bean.BeanUtil;
import com.example.persion.pojo.User;
import com.example.persion.service.UserService;
import com.example.persion.util.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//  将封装后的jwt 传入到自定义的Realm中  在到数据库中 进行一个匹配  匹配对应的用户状态
//  之后将 用户信息状态  返回给Shiro
@Component
public class AccountRealm extends AuthorizingRealm{


    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;



    @Override
    public boolean supports(AuthenticationToken token){
        return token instanceof  JwtToken;
    }


    // 拿到用户之后  获取其中对应的权限   将权限信息 封装在info中 返回给前端
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    // 进行身份验证的   密码逻辑校验
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        JwtToken jwtToken = (JwtToken)  authenticationToken;

        String userId = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();


        User user = userService.getById(Long.valueOf(userId));

        if(user == null){
            throw new UnknownAccountException("账户不存在");
        }

        if(user.getStatus() == -1){
            throw new LockedAccountException("已经被锁定");
        }


        AccountProfile profile = new AccountProfile();

        BeanUtil.copyProperties(user,profile);

        return new SimpleAuthenticationInfo(profile,jwtToken.getCredentials(),getName());
    }
}
